#include <51func.h>
void A(){
    printf("before A\n");
    sleep(3);
    printf("after A\n");
}
void B(){
    printf("before B\n");
    sleep(3);
    printf("after B\n");
}
typedef struct shareRes_s {
    int flag; //条件 0 A没做完 1 A做完了
    pthread_mutex_t mutex;// 锁保护条件资源
    pthread_cond_t cond;// 条件变量
} shareRes_t;
void * threadFunc(void *arg){
    shareRes_t * pshareRes = (shareRes_t *)arg;
    // t2
    pthread_mutex_lock(&pshareRes->mutex); //先加锁
    if(pshareRes->flag == 0){
        // 只有在A没有做完的情况下，才需要等待
        // 检查加锁-->移入唤醒队列-->解锁并陷入等待
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);
        // 加锁-->返回 之后的带锁运行
    }
    pthread_mutex_unlock(&pshareRes->mutex);
    B();
    pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,&shareRes);
    // t1
    A();
    pthread_mutex_lock(&shareRes.mutex);
    shareRes.flag  = 1;
    pthread_cond_signal(&shareRes.cond); //cond_signal unlock可以交换顺序
    pthread_mutex_unlock(&shareRes.mutex);

    pthread_join(tid,NULL);
    return 0;
}

